from django.core.exceptions import ValidationError
from rest_framework.decorators import api_view
from userapp.models import CustomUser
from utils.MobilePhoneValidator import validate_phone
from utils.jwt_util import jwt_token
from utils.response import ErrorResponse, SuccessResponse


@api_view(['POST'])
def register_login(request):
    mobile_phone = str(request.data['mobile']).strip()
    sms_code = str(request.data['sms_code']).strip()
    password = '123456'

    try:
        validate_phone(mobile_phone)  # 验证手机号
    except ValidationError as e:
        return ErrorResponse(msg='您输入的手机号码格式有误')

    # 校验验证码
    # redis_conn = get_redis_connection('verify_codes')
    # real_sms_code = redis_conn.get('sms_%s' % mobile_phone)
    # # 向redis存储数据时都是以字条串进行存储的,取出来后都是bytes类型 [bytes],需要decode()解码
    # if real_sms_code is None or sms_code != real_sms_code.decode():
    #     return ErrorResponse(msg='您输入的验证码有误')

    user = CustomUser.objects.filter(mobile_phone=mobile_phone)
    if len(user) > 0:
        # 已经注册，直接登录
        token = jwt_token(user.first())  # 工具类生成token
        data = {
            'id': user.first().id,
            'username': user.first().username,
            'token': token,
        }
        return SuccessResponse(msg='登录成功', data=data)
    else:
        # 没有注册，注册后登录
        user = CustomUser.objects.create_user(username=mobile_phone, password=password, is_active=True,
                                              mobile_phone=mobile_phone)
        if user:
            token = jwt_token(user)  # 工具类生成token
            data = {
                'id': user.id,
                'username': user.username,
                'token': token,
            }
            return SuccessResponse(msg='注册成功', data=data)
        else:
            return ErrorResponse(msg='注册失败请重试！')
